package com.bihua.iot.dynamicCompilation.service;


import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;

import com.bihua.iot.dynamicCompilation.ClassInjector;
import com.bihua.iot.dynamicCompilation.DynamicClassLoader;
import com.bihua.iot.dynamicCompilation.DynamicLoaderEngine;
import com.bihua.iot.dynamicCompilation.bytecode.InjectionSystem;


/**
 * 动态执行服务
 *
 * @author thinglinks
 * @date 2022-07-04
 *
 */
public class JavaExecuteService {
    /**
     * 动态执行代码</BR>
     * 1、使用自定义类加载器加载类</BR>
     * 2、修改类中的java.lang.System类为InjectionSystem</BR>
     * 3、将InjectionSystem的out输出到ByteArrayOutputStream</BR>
     * 4、执行过程中的所有错误都整理成字符串返回</BR>
     * 5、类中的执行结果也通过字符串返回</BR>
     * 6、4和5的输出结果不会同时存在</BR>
     * 
     * @param protocolContent 设备唯一标识
     * @param mesBody 设备唯一标识
     * @return 返回错误或者类的执行输出
     */
    public static String executeDynamically(String protocolContent, String mesBody) {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        PrintWriter out = new PrintWriter(buffer, true);
        //传入要执行的代码
        byte[] classBytes = DynamicLoaderEngine.compile(protocolContent, out, null);
        byte[] injectedClass = ClassInjector.injectSystem(classBytes);
        InjectionSystem.inject(null, new PrintStream(buffer, true), null);
        DynamicClassLoader classLoader = new DynamicClassLoader(JavaExecuteService.class.getClassLoader());
        DynamicLoaderEngine.executeMain(classLoader, injectedClass, out, mesBody);
        return buffer.toString().trim();
    }
}
